package com.ruoyi.system.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ruoyi.system.domain.NewJiaoan;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;
import org.json.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

@RestController
@RequestMapping("/pdf")
public class OcrController {
    //设置APPID/AK/SK
    public static final String APP_ID = "111";
    public static final String API_KEY = "11";
    public static final String SECRET_KEY = "111";





    public static void docAnalysisOffice() {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        byte[] pdf_file =readFile("D:\\八年级上册数学北京版电子课本.pdf") ;

        //
        JSONObject pdfResult = client.docAnalysisOfficePdf(pdf_file, 1, null);
        System.out.println("pdfResult:"+pdfResult);

        // 如果有可选参数
        HashMap<String, Object> option = new HashMap<>();
        option.put("result_type", "small");
        JSONObject pdfResultOption = client.docAnalysisOfficePdf(pdf_file, 1, option);
        System.out.println("pdfResultOption:"+pdfResultOption);
    }


    // 定义 readFile 方法
    private static byte[] readFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在: " + filePath);
            return null;
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static int getPDFPageCount(String filePath) {
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            return document.getNumberOfPages();
        } catch (IOException e) {
            e.printStackTrace();
            return -1; // 返回-1表示获取页数失败
        }
    }

    @GetMapping("/pdfText")
    public NewJiaoan pdfText(NewJiaoan newJiaoan) {
        String pdfPath = "D:\\ruoyi\\uploadPath" + newJiaoan.getJiaocaiPath().substring(8);
        String imageOutputDir = "D:\\ruoyi\\uploadPath\\images"; // 图片输出目录

        // 提取文本
        String fullText = extractPDFText(pdfPath);
        System.out.println("PDF全文内容：\n" + fullText);
        newJiaoan.setJiaocai(fullText);

        // 提取图片
        List<String> images = extractPDFImages(pdfPath, imageOutputDir);
        System.out.println("提取到的图片路径：" + images);
        newJiaoan.setImagesList(images);

        // 原有OCR处理
//        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
//        byte[] pdf_file = readFile(pdfPath);

        return newJiaoan;
    }

    // 提取PDF全部文本
    private static String extractPDFText(String filePath) {
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        } catch (IOException e) {
            e.printStackTrace();
            return "文本提取失败：" + e.getMessage();
        }
    }

    // 提取PDF全部图片
    private static List<String> extractPDFImages(String filePath, String outputDir) {
        List<String> imagePaths = new ArrayList<>();
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            PDPageTree pages = document.getPages();
            int imageCounter = 1;

            // 尺寸过滤阈值配置（单位：像素）
            final int MIN_WIDTH = 200;  // 最小宽度
            final int MIN_HEIGHT = 200; // 最小高度

            // 确保输出目录存在
            File outputDirFile = new File(outputDir);
            if (!outputDirFile.exists()) {
                outputDirFile.mkdirs();
            }

            for (int i = 0; i < pages.getCount(); i++) {
                PDResources resources = pages.get(i).getResources();
                for (COSName xObjectName : resources.getXObjectNames()) {
                    PDXObject xObject = resources.getXObject(xObjectName);
                    if (xObject instanceof PDImageXObject) {
                        PDImageXObject image = (PDImageXObject) xObject;
                        BufferedImage bufferedImage = image.getImage();
                        // 获取图片尺寸
                        int width = bufferedImage.getWidth();
                        int height = bufferedImage.getHeight();

                        // 尺寸过滤判断
                        if (width < MIN_WIDTH || height < MIN_HEIGHT) {
                            System.out.printf("跳过小图片：%dx%d 页数：%d%n", width, height, i+1);
                            continue;
                        }

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
                        String format = sdf.format(new Date());


                        String fileName = outputDir + File.separator +format+
                                "page_" + (i+1) + "_image_" + imageCounter + ".png";

                        try {
                            ImageIO.write(bufferedImage, "PNG", new File(fileName));
                            imagePaths.add(fileName);
                            imageCounter++;
                        } catch (IOException e) {
                            System.err.println("图片保存失败：" + fileName);
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imagePaths;
    }





}
